<?php
/**
 * Created by PhpStorm.
 * User: TianFeng
 * Date: 2018/1/10
 * Time: 10:58
 * FTP上传类
 */
namespace app\common\lib;
use phpDocumentor\Reflection\Types\Self_;
use think\Controller;
use think\Exception;

class Sftp {
    const sinapay_sftp_address='222.73.39.37';
    const sinapay_sftp_port='50022';
    const sinapay_sftp_Username='200004595271';
    const sinapay_sftp_privatekey='/usr/local/data/ssh/id_rsa';
    const sinapay_sftp_publickey = '/usr/local/data/ssh/id_rsa.pub';

    public function sftp_upload($file,$filename) {
        $strServer = self::sinapay_sftp_address;
//        Log::Info("sftp连接地址,数据:".$strServer);
        $strServerPort = self::sinapay_sftp_port;
//        Log::Info("sftp连接端口,数据:".$strServerPort);
        $strServerUsername = self::sinapay_sftp_Username;
//        Log::Info("sftp连接用户名,数据:".$strServerUsername);
        $strServerprivatekey = self::sinapay_sftp_privatekey;
//        Log::Info("sftp连接私钥,数据:".sinapay_sftp_privatekey);
        $strServerpublickey = self::sinapay_sftp_publickey;
//        Log::Info("sftp连接公钥,数据:".sinapay_sftp_publickey);
//        Log::Info("ssh2_connect status,数据:".print_r(get_extension_funcs("ssh2_connect")));
        $resConnection = ssh2_connect($strServer,$strServerPort, array('hostkey'=>'ssh-rsa'));

        if (ssh2_auth_pubkey_file ($resConnection, $strServerUsername, $strServerpublickey, $strServerprivatekey ))
        {
            $sftp = ssh2_sftp($resConnection);
            $stream = @fopen("ssh2.sftp://" .(int)$sftp ."/upload/$filename", 'w');
            if (!$stream){
                //echo "Could not open file: "."/upload/$filename";
                return false;
            }

            $data_to_send = @file_get_contents($file);
            if ($data_to_send === false){
                //echo 'out file';
                return false;
            }
            fwrite($stream, $data_to_send);
            fclose($stream);

            return true;
        }
        return false;
    }
}
